package com.access.config;

import cn.hutool.core.util.StrUtil;
import com.access.trace.Constant;
import com.alibaba.ttl.TransmittableThreadLocal;
import org.slf4j.MDC;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @author: lei
 * @date: 2024-08-22 16:40
 * @desc:
 */

public class TraceIdInterceptor implements HandlerInterceptor {

    public static final ThreadLocal<Map<String, String>> MDC_INFORMATION = new TransmittableThreadLocal<Map<String, String>>(){
        @Override
        protected void beforeExecute() {
            Map<String, String> mdc = get();
            mdc.forEach(MDC::put);
        }

        @Override
        protected void afterExecute() {
            MDC.clear();
        }

        @Override
        protected Map<String, String> initialValue() {
            return new HashMap<>();
        }
    };

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String traceId = request.getHeader(Constant.TRACE_ID);
        if (StrUtil.isBlank(traceId)) {
            // 从外部来的请求,traceId由网管传递，但存在内部定时任务情况，调用下游服务时,下游服务没有traceId，需要重新生成
            traceId = UUID.randomUUID().toString();
        }
        MDC.put(Constant.TRACE_ID, traceId);
        //同时给TransmittableThreadLocal记录traceId
        MDC_INFORMATION.get().put(Constant.TRACE_ID, traceId);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        //清除数据
        MDC.clear();
        MDC_INFORMATION.get().clear();
        MDC_INFORMATION.remove();
    }
}
